package com.myxml;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import java.io.FileWriter;

public class XmlCreator {
    public static void main(String[] args) {
        try {
            // 1. 创建文档和根元素
            Document document = DocumentHelper.createDocument();
            Element bookstore = document.addElement("bookstore");
            
            // 2. 添加第一本书
            Element book1 = bookstore.addElement("book")
                .addAttribute("id", "b201")
                .addAttribute("category", "设计");
            
            book1.addElement("title").addAttribute("lang", "zh")
                  .addText("设计模式：可复用面向对象软件的基础");
            book1.addElement("author").addText("Erich Gamma");
            book1.addElement("year").addText("2020");
            book1.addElement("price").addText("79.00");
            
            // 3. 添加第二本书
            Element book2 = bookstore.addElement("book")
                .addAttribute("id", "b202")
                .addAttribute("category", "架构");
            
            book2.addElement("title").addAttribute("lang", "en")
                  .addText("Clean Architecture");
            book2.addElement("author").addText("Robert C. Martin");
            book2.addElement("year").addText("2017");
            book2.addElement("price").addText("99.00");
            
            // 4. 格式化输出到文件
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("UTF-8");
            
            XMLWriter writer = new XMLWriter(
                new FileWriter("new_books.xml"), format
            );
            writer.write(document);
            writer.close();
            
            System.out.println("XML文件创建成功！");
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}